<?php

namespace App\Library\SMS\aliyunsdk;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Exceptions\ApicrzsExceptions;
use App\Exceptions\ApiException;
use Darabonba\OpenApi\Models\Config;
use Illuminate\Support\Facades\Log;

class SmsClient
{

    protected static $accessKeyId = "LTAI5tLZjD4Zi5TSW3JV1gwb";
    protected static $accessKeySecret = "ehVUKVkQRupf0oZDgA9vmXEdQe2BZu";
    protected static $signName = "甄生活";
    protected static $endpoint = "dysmsapi.aliyuncs.com";
    protected static $templateCode = "SMS_478215093";

    public static function apiAliyunSms($phone,$code,$tempCode,$time){
        $client = self::createClient(config('grzq_sms.aliyun.key'), config('grzq_sms.aliyun.secret'));
        $signName = config('grzq_sms.aliyun.signName');
        $templateCode = config('grzq_sms.aliyun.templateCode.'.$signName.'.'.$tempCode)??config('grzq_sms.aliyun.templateCode.'.$signName.'.dynamics');
        $data_content = ['code'=>$code,'time'=>$time];
        $sendSmsRequest = new SendSmsRequest([
            "signName" => $signName,
            "templateCode" => $templateCode,
            "phoneNumbers" => "$phone",
            "templateParam" => json_encode($data_content)
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $request = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            xdebug($request,'短信','aliyun/sms');
            if (isset($request) && $request->body->code !== 'OK') {
                throw new ApiException('发送失败');
            }
            return [
                'requestId' => $request->body->requestId,
                'content' => json_encode($data_content),
                'template' => $templateCode
            ];
        }catch (\Exception $e){
//            throw new ApiException('【阿里云平台错误提示】：' . $e->getMessage());
            throw new ApicrzsExceptions('发送失败');
        }

    }
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId,$accessKeySecret){
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => $accessKeyId,
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }
}
